package com.iris.live.services.data.repositories.impl;

import com.google.common.base.Strings;
import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.common.StringUtils;
import com.iris.live.services.data.repositories.FileRepository;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by Xin on 7/13/2016.
 */
@Repository
public class FileRepositoryImpl implements FileRepository {
    private static final Logger logger = LoggerFactory.getLogger(FileRepositoryImpl.class);

    @Value("${upload.path}")
    private String path;
    private Path dir;
    @Autowired
    private Environment env;

    @PostConstruct
    public void init() {
        this.dir = Paths.get(this.path);
    }

    @Override
    public String save(InputStream input, String fileName) {
        Path path = this.randomPath(fileName);
        try {
            Path fullPath = this.dir.resolve(path);
            this.confirmDir(fullPath);
            Files.copy(input, fullPath);
            return path.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void fetch(OutputStream output, String pathStr) {
        Path path = Paths.get(pathStr);
        try {
            Path fullPath = this.dir.resolve(path);
            Files.copy(fullPath, output);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void confirmDir(Path file) {
        Path dir = file.getParent();
        if (!Files.exists(dir)) {
            try {
                Files.createDirectories(dir);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        Assert.isTrue(Files.isDirectory(dir));
        Assert.isTrue(Files.isReadable(dir));
        Assert.isTrue(Files.isWritable(dir));
    }

    private Path randomPath(String file) {
        Date now = new Date();
        SimpleDateFormat pattern = new SimpleDateFormat("./yyyy/MM/dd/");
        String fileName = UUID.randomUUID().toString();
        String ext = FilenameUtils.getExtension(file);
        if (!Strings.isNullOrEmpty(ext)) {
            fileName += ("." + ext);
        }

        return Paths.get(pattern.format(now) + fileName);
    }

    public String uploadFile (MultipartFile file, String permit,String name) {
        String fullPath, uploadExcelDir = env.getProperty("upload.excel.dir");
        if(StringUtils.isNullOrBlank(uploadExcelDir)){
            uploadExcelDir = "./upload/excels/" ;
        }
        OutputStream localFile = null;
        try{
            File oFile = new File(uploadExcelDir);
            if(! oFile.exists()){
                oFile.mkdirs();
            }
             fullPath = permit + "_"+name + DateFormatUtils.getFormatDateToString(new Date(), "yyyyMMdd_HHmmss") + "_" + UUID.randomUUID()
                    + "_" + file.getOriginalFilename();
            localFile = new FileOutputStream(new File(uploadExcelDir + fullPath));
            FileCopyUtils.copy(file.getInputStream(), localFile);
        }catch(Exception exc){
            logger.error("保存上传文件异常。", exc);
            return null;
        }finally{
            if(localFile != null){
                try {
                    localFile.flush();
                    localFile.close();
                }catch(Exception exc){
                    logger.error("保存上传文件异常。", exc);
                    return null;
                }
            }
        }
        return fullPath;
    }
}
